<?php

namespace addons\cms\controller\api;

use addons\cms\library\CommentException;
use think\Config;
use think\Exception;

/**
 * 评论
 */
class Comment extends Base
{
    protected $noNeedLogin = ['index'];

    public function _initialize()
    {
        parent::_initialize();
        $type = $this->request->post("type", "archives");
        if ($type == 'archives') {
            //检测ID是否加密
            $this->hashids('aid');
        }
    }

    /**
     * 评论列表
     */
    public function index()
    {
        $aid = (int)$this->request->param('aid');
        $type = $this->request->post('type', 'archives');
        $list = \addons\cms\model\Comment::with('user')
            ->where(['aid' => $aid, 'type' => $type])
            ->field('id,aid,user_id,content,ip_address,createtime,updatetime,type,updatetime')
            ->order('id desc')
            ->paginate(10);
        if ($list){
            $list = $list->toArray();
            if (getHeaderLang() != getDefaultLang()){
                languageTranslation($list, getHeaderLang(),['ip_address']);
            }
        }
//        Config::set('paginate.page', $page);
//        $commentList = \addons\cms\model\Comment::getCommentList(['aid' => $aid]);
//
//        $commentList = $commentList->getCollection();
//        foreach ($commentList as $index => $item) {
//            if ($item->user) {
//                $item->user->avatar = cdnurl($item->user->avatar, true);
//                $item->user->visible(explode(',', 'id,nickname,avatar'));
//            }
//            $item->hidden(['ip', 'useragent', 'deletetime', 'aid', 'subscribe', 'status', 'type', 'updatetime']);
//        }
        $this->success('', $list);
    }

    /**
     * 发表评论
     */
    public function post()
    {
        try {
            $params = $this->request->post();
            if (!isset($params['type'])){
                $params['type'] = 'archives';
            }
            $comment = \addons\cms\model\Comment::postComment($params);

            $comment['comment']->user->visible(explode(',', 'id,nickname,avatar'));
            $comment['comment']->user->avatar = cdnurl($comment['comment']->user->avatar, true);

        } catch (Exception $e) {
            $this->error('The operation failed');
        }

        $this->success(__('The review was successful'), ['comment' => $comment['comment'], 'score' => $comment['score']]);
    }
}
